import Storage from './storage';
import * as Prefs from '../constants/PreferenceKey';

let cookie = null;
let diseaseConf = null;

async function getCookie() {
  if (cookie) {
    return cookie;
  }
  cookie = await Storage.get(Prefs.USER_COOKIE);
  return cookie;
}

async function setCookie(ck) {
  try {
    await Storage.set(Prefs.USER_COOKIE, ck);
    cookie = ck;
  } catch (error) {
    // empty
  }
}

async function getDiseaseConf() {
  try {
    if (diseaseConf) {
      return diseaseConf;
    }
    diseaseConf = await Storage.get(Prefs.DISEASE_CONF);
    return diseaseConf;
  } catch (error) {
    return null;
  }
}

async function setDiseaseConf(conf) {
  try {
    await Storage.set(Prefs.DISEASE_CONF, conf);
    diseaseConf = null;
  } catch (error) {
    // empty
  }
}

async function logout() {
  await Storage.remove(Prefs.USER_COOKIE);
  // 暂时去掉这一行，因为逻辑代码中很多地方需要userId，如果remove掉会造成闪退
  // await Storage.remove(Prefs.USER_DATA_KEY);
  await Storage.remove(Prefs.USER_PERMISSION);
  await Storage.remove(Prefs.USER_MODULES);
}

async function setCancelUpdate(ver) {
  try {
    await Storage.set(Prefs.CANCEL_UPDATE, ver);
  } catch (error) {
    // empty
  }
}

async function getCancelUpdate() {
  try {
    const ver = await Storage.get(Prefs.CANCEL_UPDATE);
    return ver;
  } catch (error) {
    return null;
  }
}

async function setRegisterID(id) {
  try {
    await Storage.set(Prefs.REGISTERID, id);
  } catch (err) {
    // empty
  }
}

async function getRegisterID() {
  try {
    const ret = await Storage.get(Prefs.REGISTERID);
    return ret;
  } catch (err) {
    return '';
  }
}

export default {
  getCookie,
  setCookie,
  getDiseaseConf,
  setDiseaseConf,
  getCancelUpdate,
  setCancelUpdate,
  logout,
  setRegisterID,
  getRegisterID,
};
